package com.ims.common.dao;

import static org.hibernate.criterion.Example.create;

import java.io.Serializable;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.impl.SessionImpl;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseDAOHibImpl<T, ID extends Serializable> extends HibernateDaoSupport implements
		BaseDAO<T, ID> {

	private static final Logger	LOG	= Logger.getLogger(BaseDAOHibImpl.class);

	@Override
	public List<?> find(String hqlQuery, Object[] params) {
		// TODO Auto-generated method stub
		return (List<?>) getHibernateTemplate().find(hqlQuery, params);
	}

	@Override
	public void persistObject(T entity) {
		// TODO Auto-generated method stub
		getHibernateTemplate().persist(entity);
		Object val = getId(entity);
		LOG.info(String.format("Saved Entry %s#%s", entity.getClass().getName(), val));
	}

	@Override
	public void updateObject(T entity) {
		// TODO Auto-generated method stub
		getHibernateTemplate().update(entity);
	}

	@Override
	public void delete(T entity) {
		// TODO Auto-generated method stub
		Object val = getId(entity);
		LOG.info(String.format("Deleting Entry %s#%s", entity.getClass().getName(), val));
		getHibernateTemplate().delete(entity);
	}

	@Override
	public T findById(Class<T> type, ID id) {
		// TODO Auto-generated method stub
		return getHibernateTemplate().get(type, id);
	}


	@Override
	public List<T> findAll(Class<T> type) {
		// TODO Auto-generated method stub
		return (List<T>) getHibernateTemplate().loadAll(type);
	}

	protected Object getId(T entity) {
		SessionImpl sessionImpl = (SessionImpl) getSession();
		Serializable id = (Serializable) sessionImpl.getIdentifier(entity);
		return id;
	}

	@Override
	public void saveOrUpdateObject(T entity) {
		// TODO Auto-generated method stub
		 getHibernateTemplate().saveOrUpdate(entity);
	}
	
/*	public List<Address> findByExample(Address instance) {
		log.debug("finding Address instance by example");
		try {
			List<Address> results = (List<Address>) sessionFactory
					.getCurrentSession()
					.createCriteria("com.ims.stocks.model.Address")
					.add(create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}*/
}
